package com.hd.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.hd.controller.base.BaseController;
import com.hd.entity.Attach;
import com.hd.service.AttachService;
import com.hd.util.Const;
import com.hd.util.FileUtil;
import com.hd.util.ZipUtils;
import com.hd.util.result.EditormdResult;

/**
 * 上传
 */
@RequestMapping("/upload")
@Controller
public class UploadController extends BaseController {
    @Autowired
    private AttachService attachService;
    
    /**
     * 上传附件
     * 返回 附件id集合
     * @param request
     * @param response
     * @return
     * @throws IllegalStateException
     * @throws IOException
     */
    @RequestMapping(value="/upload")
    @ResponseBody
    public Object upload(HttpServletRequest request,
                            HttpServletResponse response)
            throws IllegalStateException, IOException {
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        String filePaths="";
        String attachIds="";//返回附件id集合
        List<Attach>attachList=new ArrayList<Attach>();
        if (multipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            Iterator<String> iter = multiRequest.getFileNames();
            while (iter.hasNext()) {
                MultipartFile file = multiRequest.getFile(iter.next());
                if (file != null) {
                    String myFileName = file.getOriginalFilename();
                    if (myFileName.trim() != "") {
                        String fileName = file.getOriginalFilename();
                        String fileExt = fileName.substring(
                                fileName.lastIndexOf(".") + 1).toLowerCase();
                        SimpleDateFormat df = new SimpleDateFormat(
                                "yyyyMMddHHmmss");
                        String newFileName = df.format(new Date());
                        String fileNames = newFileName
                                + new Random().nextInt(1000) + "." + fileExt;
                        df= new SimpleDateFormat(
                                "yyyyMMdd");
                        String basePath= df.format(new Date()) +"/"+ fileNames;
                        String base= "/upload/"+basePath;
                        String path=Const.BASE_UPLOAD_PATH+base;
                        System.out.println("path:"+path);
                        File localFile = new File(path);
                        if (!localFile.exists()) {// 如果文件夹不存在，自动创建
                            localFile.mkdirs();
                        }
                        file.transferTo(localFile);
                        //保存附件
                        Attach attach=new Attach();
                        attach.setId(UUID.randomUUID().toString());
                        attach.setCreateTime(new Date());
                        attach.setName(fileName);
                        attach.setType(fileExt);
                        attach.setPath(base);
                        attachService.save(attach);
                        //保存路径
                        filePaths+=base+",";
                        attachIds+=attachIds+",";
                        attachList.add(attach);
                    }
                }
            }
            if(!filePaths.equals("")){
                filePaths=filePaths.substring(0,filePaths.lastIndexOf(","));
            }
            if(!attachIds.equals("")){
            	attachIds=attachIds.substring(0,attachIds.lastIndexOf(","));
            }
        }
        return renderSuccess(attachList);
    }
    /**
     * 上传附件
     * 返回 附件id集合
     * @param request
     * @param response
     * @return
     * @throws IllegalStateException
     * @throws IOException
     */
    @RequestMapping(value="/uploadEditormd",method=RequestMethod.POST)
    @ResponseBody
    public Object uploadEditor(HttpServletRequest request,
    		HttpServletResponse response)
    				throws IllegalStateException, IOException {
    	CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
    			request.getSession().getServletContext());
    	String filePath="";
    	String attachIds="";//返回附件id集合
    	List<Attach>attachList=new ArrayList<Attach>();
    	if (multipartResolver.isMultipart(request)) {
    		MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
    		Iterator<String> iter = multiRequest.getFileNames();
    		while (iter.hasNext()) {
    			MultipartFile file = multiRequest.getFile(iter.next());
    			if (file != null) {
    				String myFileName = file.getOriginalFilename();
    				if (myFileName.trim() != "") {
    					String fileName = file.getOriginalFilename();
    					String fileExt = fileName.substring(
    							fileName.lastIndexOf(".") + 1).toLowerCase();
    					SimpleDateFormat df = new SimpleDateFormat(
    							"yyyyMMddHHmmss");
    					String newFileName = df.format(new Date());
    					String fileNames = newFileName
    							+ new Random().nextInt(1000) + "." + fileExt;
    					df= new SimpleDateFormat(
    							"yyyyMMdd");
    					String basePath= df.format(new Date()) +"/"+ fileNames;
    					String base= "/upload/"+basePath;
    					String path=Const.BASE_UPLOAD_PATH+base;
    					System.out.println("path:"+path);
    					File localFile = new File(path);
    					if (!localFile.exists()) {// 如果文件夹不存在，自动创建
    						localFile.mkdirs();
    					}
    					file.transferTo(localFile);
    					//保存附件
    					Attach attach=new Attach();
    					attach.setId(UUID.randomUUID().toString());
    					attach.setCreateTime(new Date());
    					attach.setName(fileName);
    					attach.setType(fileExt);
    					attach.setPath(base);
    					attachService.save(attach);
    					//保存路径
    					filePath=base;
    				}
    			}
    		}
    	}
    	EditormdResult result=new EditormdResult();
    	result.setMessage("上传成功！");
    	result.setSuccess(1);
    	result.setUrl(Const.ATTACH_URL+filePath);
    	return result;
    }
    
    //删除附件
    @ResponseBody
    @RequestMapping("/attach/delete/{id}")
    public Object deleteAttach(@PathVariable("id")String id) {
    	//在磁盘上删除文件
    	Attach attach=attachService.get(id);
    	if(attach!=null) {
	    	String path=Const.BASE_UPLOAD_PATH+attach.getPath();
	    	File f=new File(path);
	    	if(f.exists()) {
	    		f.delete();
	    	}
	    	attachService.delete(id);
    	}
    	return renderSuccess("删除成功！");
    }
    //删除附件
    @ResponseBody
    @RequestMapping("/attach/delete2/{id}")
    public Object deleteAttach2(@PathVariable("id")String id) {
    	//在磁盘上删除文件
    	Attach attach=attachService.get(id);
    	if(attach!=null) {
    		String path=Const.BASE_UPLOAD_PATH+attach.getPath();
    		File f=new File(path);
    		if(f.exists()) {
    			f.delete();
    		}
    		attachService.delete(id);
    	}
    	return renderSuccess("",id);
    }
    /**
     * 下载附件
     * @param id
     * @throws Exception 
     */
    @RequestMapping("/downloadAttach/{id}")
    public void downloadAttach(@PathVariable("id")String id,HttpServletRequest request,
    		HttpServletResponse response) throws Exception {
    	Attach attach = attachService.get(id);
    	String filename=attach.getName();
    	String filePath=Const.BASE_UPLOAD_PATH+attach.getPath();
    	System.out.println(filePath);
    	System.out.println(filename);
    	download(filename,filePath,request,response);
    }
    
    /**
     * 压缩下载附件
     * @param attachIds
     * @param name
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("/zipDownloadAttach")
    public void zipDownloadAttach(String attachIds,String name,HttpServletRequest request,
    		HttpServletResponse response) throws Exception {
		// 压缩文件夹
		// 1、临时文件
		String save = Const.BASE_UPLOAD_PATH;
		File zipRootFile = new File(save + "/zipAttach");
		if (!zipRootFile.exists()) {
			zipRootFile.mkdirs();
		}
		File zipChildFile=new  File(save + "/zipAttach/"+name);
		if (!zipChildFile.exists()) {
			zipChildFile.mkdirs();
		}
		//复制文件
		String attachIdArr[]=attachIds.split(",");
    	for(String attachId:attachIdArr) {
    		Attach attach = attachService.get(attachId);
    		String sourcePath=Const.BASE_UPLOAD_PATH+attach.getPath();
    		String fileName=attach.getName();
    		File source=new File(sourcePath);
    		String destPath=save + "/zipAttach/"+name+"/"+fileName;
    		File dest=new File(destPath);
    		FileUtil.copyFileUsingApacheCommonsIO(source, dest);
    	}
		String basezip = save + "/zipAttach/" + name;
		String targetPath=save + "/zipAttach";
		basezip=basezip.replace("//", "/");
		basezip=basezip.replace("/", "\\");
		targetPath=targetPath.replace("//", "/");
		targetPath=targetPath.replace("/", "\\");
		System.out.println(basezip);
		System.out.println(targetPath);
		ZipUtils.zip(basezip,targetPath, name + ".zip");
		// 取出文件夹放入流中
		String zipFile =save + "/zipAttach/" + name + ".zip";
		download(name + ".zip", zipFile, request, response);

		// 下载后删除文件
		// ①删除压缩文件
		FileUtil.deleteChildrenFile(zipRootFile);
    }
    
    @RequestMapping(value="/uploadfile",method=RequestMethod.POST)
    public void hello(HttpServletRequest request,HttpServletResponse response,@RequestParam(value = "editormd-image-file", required = false) MultipartFile attach){
        try {
            request.setCharacterEncoding( "utf-8" );
            response.setHeader( "Content-Type" , "text/html" );
            String rootPath = request.getSession().getServletContext().getRealPath("/upload/");

            /**
             * 文件路径不存在则需要创建文件路径
             */
            File filePath=new File(rootPath);
            if(!filePath.exists()){
                filePath.mkdirs();
            }

            //最终文件名
            File realFile=new File(rootPath+File.separator+attach.getOriginalFilename());
            FileUtils.copyInputStreamToFile(attach.getInputStream(), realFile);

            //下面response返回的json格式是editor.md所限制的，规范输出就OK
            response.getWriter().write( "{\"success\": 1, \"message\":\"上传成功\",\"url\":\"/upload/" + attach.getOriginalFilename() + "\"}" );
        } catch (Exception e) {
            try {
                response.getWriter().write( "{\"success\":0}" );
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }
    
    /***************************************分片上传*******************************************************/


	/**
	 * 读取图片，以流的形式输出
	 */
	@RequestMapping("/readImg")
	public void readImg(String id,HttpServletRequest request,HttpServletResponse response){
			// response.setContentType("image/*");
			FileInputStream fis = null;
			OutputStream os = null;
			try {
				Attach attach=attachService.get(id);
				fis = new FileInputStream(Const.BASE_UPLOAD_PATH+attach.getPath());
				os = response.getOutputStream();
				int count = 0;
				byte[] buffer = new byte[1024 * 8];
				while ((count = fis.read(buffer)) != -1) {
					os.write(buffer, 0, count);
					os.flush();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			try {
				fis.close();
				os.close();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
}

